package com.cxz.study.ddd_project.infrastructure.service;

import com.cxz.study.ddd_project_parent_common.enums.StateCode;
import jakarta.annotation.Resource;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Set;


/**
 * @className: LtcValidator
 * @author: ocxz1
 * @date: 2025/1/1 下午4:36
 * @Version: 1.0
 * @description: anneng-ltc-change-v1.0 参数校验器
 */
@Component
public class LtcValidator {

    @Resource
    private Validator validator;

    /**
     * 参数检查
     * @param param 检查的参数
     * @param logger 日志记录对象
     * @return ture：检查通过，false：检查不通过
     * @param <V>
     */
    public <V> boolean checkParam(V param, Logger logger) {
        if (Objects.isNull(param)) {
            logger.error(StateCode.PARAMS_NOT_ENOUGH.text);
        }

        // 数据检查
        Set<ConstraintViolation<V>> validate = validator.validate(param);

        if (!validate.isEmpty()) {
            StringBuilder errorMessages = new StringBuilder("Validation failed for fields: ");
            for (ConstraintViolation<V> violation : validate) {
                errorMessages.append("\n - ")
                        .append(violation.getPropertyPath())
                        .append(": ")
                        .append(violation.getMessage());
                // 记录每个验证错误
//                logger.warn("Validation error for field {}: {}",
//                        violation.getPropertyPath(),
//                        violation.getMessage());
            }
            logger.warn(errorMessages.toString());
        }
        return true;
    }
}
